package com.link.base.base.user.service;

import com.link.base.base.user.model.User;
import com.link.base.base.user.dao.mybatis.mapper.LoginLogMapper;
import com.link.base.base.user.model.LoginDTO;
import com.link.base.base.user.model.LoginLog;
import com.link.base.base.user.model.RespDTO;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.cllog.LCLogger;
import com.link.core.util.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author unknown
 * @date unknown
 * @comments 登录日志
 */
@Service
public class LoginLogServiceImpl extends BasicServiceImpl<LoginLog> implements LoginLogService {

    @Resource
    private LoginLogMapper loginLogMapper;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Override
    public BasicMapper<LoginLog> getBasicMapper() {
        return loginLogMapper;
    }

    @Override
    public void deleteByUserId(String userId) throws ServiceException {


    }

    @Override
    public void addLoginSuccessLog(LoginLog record) throws ServiceException {
        try {
            loginLogMapper.addLoginSuccessLog(record);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public void addLoginFailLog(LoginLog record) throws ServiceException {
        try {
            record.setId(keyGenerateDao.keyGenerate());
            loginLogMapper.addLoginFailLog(record);
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public void addLoginLogByRespDTO(RespDTO dto, HttpServletRequest request) {
        LoginDTO loginDTO = (LoginDTO) dto.getData();
        User user = loginDTO.getUser();
        //IpUtil获取IP地址
        String ip = IpUtil.getIpAddress(request);
        LoginLog record = new LoginLog();
        record.setLockFlag('N');
        String userAgent = request.getHeader("User-Agent");
        record.setUserId(user.getId());
        record.setLoginName(user.getUsername());
        record.setIpAddress(ip);
        record.setUserAgent(userAgent);
        //crm用户登录
        record.setUserSource("CRM");
        record.setAccessToken(loginDTO.getToken());
        record.setLoginType(user.getLoginType());
        this.addLoginSuccessLog(record);
    }


}
